from utils import common
import json
import re

def transformPayload(payload):
    return bytes.fromhex(common.string_to_hex(payload))


def transformResponse(response):
    """处理HTTP RESPONSE"""
    common.print_gc_info()
    resp = response.decode()
    resp = re.sub(r"\+IPD,\d+:", "", resp)

    if "CLOSED" in resp:
        # print(resp)
        match = re.search(r"\{(.*?)CLOSED", resp)
        if match:
            json_str = "{" + match.group(1)
            data = json.loads(json_str)
            common.print_gc_info()
            return data
    else:
        json_str = format_network_response(response)
        return json_str


def format_network_response(resp):
    # raw byte
    if isinstance(resp, bytearray):
        resp = resp.decode()
        match = re.search(r"\{(.*?)\}$", resp)
        if match:
            v = match.group(0)
            with open("/response.json", "w") as f:
                f.write(v)
            json_data = json.loads(v)
            return json_data
    # json
    if isinstance(resp, dict):
        return resp

    # string
    if isinstance(resp, str):
        return resp
    return resp

def format_url(url):
    try:
        proto, dummy, host, path = url.split("/", 3)
    except ValueError:
        raise ValueError(f"{url} is not a valid uri")
    return {"proto": proto, "host": host, "path": path}

def get_search_params(path, key_name):
    try:
        symbol_index = path.find("?")
        # print(symbol_index)
        if symbol_index < 0:
            return None

        search_str = path[symbol_index + 1 :]
        # print(search_str)
        params = search_str.split("&")
        # print(params)
        for param in params:
            (key, value) = param.split("=")
            if key == key_name:
                return value
        return None
    except Exception as e:
        return None
